package com.progress.bar;

import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

public class ProgressBarActivity extends Activity implements OnClickListener {
	/** Called when the activity is first created. */

	ProgressBar bar;
	Button pause, resume, restart, servicestart;
	Thread back;
	Context cxt;
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if(isRunning) {
				bar.incrementProgressBy(2);
			}
		}
	};
	boolean isRunning = false;
	Service appsService;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		bar = (ProgressBar) findViewById(R.id.progressBar1);
		pause = (Button) findViewById(R.id.button1);
		pause.setText("Pause");
		pause.setOnClickListener(this);
		resume = (Button) findViewById(R.id.button2);
		resume.setText("Resume");
		resume.setOnClickListener(this);
		restart = (Button) findViewById(R.id.button3);
		restart.setText("Restart");
		restart.setOnClickListener(this);
		servicestart = (Button) findViewById(R.id.button4);
		servicestart.setText("Start Service");
		servicestart.setOnClickListener(this);
		
		bindService(new Intent(this, serviceclass.class), onService, Context.BIND_AUTO_CREATE);
	}
	private ServiceConnection onService = new ServiceConnection() {
		public void onServiceConnected(ComponentName className, IBinder rawBinder) {
			appsService = ((serviceclass.LocalBinder)rawBinder).getService();
		}
		public void onServiceDisconnected(ComponentName className) {
			appsService = null;
		}
	};

	public void onStart() {
		cxt = this;
		super.onStart();
		bar.setProgress(0);
		back = new Thread(new Runnable() {
			public void run() {
				try {
					while(bar.getProgress() < 100) {
						Thread.sleep(800);
						handler.sendMessage(handler.obtainMessage());
					}
				}
				catch(Throwable t) {
				}
			}
		});
		isRunning = true;
		back.start();
	}
	public void onStop() {
		super.onStop();
		isRunning = false;
	}
	public void onClick(View v) {
		if(v.equals(pause)) {
			isRunning = false;
		}
		if(v.equals(resume)) {
			isRunning = true;
		}
		if(v.equals(restart)) {
			bar.setProgress(0);
			isRunning = true;
		}
		if(v.equals(servicestart)) {
			appsService.startService(new Intent(this, serviceclass.class));
		}
	}
	public void onDestroy() {
		//ASK PRIME HOW TO DESTROY 
	}
}